package com.legsem.jhosync.ws.rs;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.legsem.jhosync.ws.HttpServer;

/**
 * Common code share by all REST resources.
 * 
 */
public abstract class AbstractResource {

    /** Locates the server implementation in the servlet session. */
    public static final String SERVER_IMPLEMENTATION_KEY = "com.legsem.jrhosync.server";

    /** A JSON mapper. */
    private ObjectMapper _mapper = new ObjectMapper();

    /**
     * The server code is cached in the session.
     * 
     * @param req an incoming http request
     * @return a server implementation
     */
    public HttpServer getServer(HttpServletRequest req) {
        HttpSession session = req.getSession(true);
        HttpServer server = (HttpServer) session
                .getAttribute(SERVER_IMPLEMENTATION_KEY);
        if (server == null) {
            server = new HttpServer(req);
            session.setAttribute(SERVER_IMPLEMENTATION_KEY, server);
        }
        return server;

    }

    public ObjectMapper getMapper() {
        return _mapper;
    }

}
